<template>
    <div>
        <div class="activity-right" @click="hideSel($event)" style="padding-top:20px;">
            <h3>添加商品</h3>
            <el-form ref="form" :rules="rules" :model="form" label-width="120px">
                <div class="form">
                    <section class="formLeft">
                        <el-form-item label="是否为爆款:">
                            <el-checkbox v-model="hotSaleStatus">{{hotSaleStatus ? '是': '否'}}</el-checkbox>
                        </el-form-item>
                        <el-form-item label="爆款开始时间:" v-if="hotSaleStatus">
                            <el-date-picker v-model="presaleTime" type="datetime"  placeholder="选择日期时间">
                            </el-date-picker>
                        </el-form-item>
                        <el-form-item label="商品名称:" prop="goodsName">
                            <el-input style="width:400px" v-model="form.goodsName" type="text"  placeholder="请输入商品名称" clearable></el-input>
                        </el-form-item>
                        <el-form-item label="商品品牌:" prop="brandArray">
                            <el-select style="width:400px" filterable v-model="form.brandId" placeholder="选择品牌">
                                <el-option v-for="item in brandArray" :key="item.value" :label="item.label" :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="活动专场:" prop="activityArray">
                            <el-select style="width:400px" filterable v-model="form.activityId" @change="getActivity" placeholder="选择活动">
                                <el-option v-for="item in activityArr" :key="item.value" :label="item.label" :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item v-if="form.activityId != null&& form.activityId" label="活动状态:" prop="activityStatus">
                            <template>{{activityStatus == 0 ? '展示' : (activityStatus == 1 ? '售卖中':(activityStatus == 2 ? '结束' :''))}}</template>
                        </el-form-item>
                        <el-form-item label="商品介绍:" prop="goodsDesc">
                            <el-input type='textarea' :rows="5" style="width:400px" v-model="form.goodsDesc"></el-input>
                        </el-form-item>
                        
                        <el-form-item label="商品编号:" prop="goodsCode">
                            <el-input style="width:400px" v-model="form.goodsCode" type="text" placeholder="请输入商品编号" clearable></el-input>
                        </el-form-item>
                        <el-form-item label="选择款数:" class="must" prop="">
                            <el-select style="width:400px" v-model="goodsItemCountVal" @change="goodsItemCountChange" placeholder="请选择">
                                <el-option
                                    v-for="item in goodsItemCount"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                    >
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="排序:" prop="sort">
                            <el-input style="width:400px" v-model="form.sort" type="text" placeholder="1开始为最小" clearable></el-input>
                        </el-form-item>
                    </section>
                    <section class="formRight">
                        <el-form-item label="商品原价:" prop="goodsPrice">
                            <el-input style="width:400px" v-model="form.goodsPrice" @change="handleOrignailChange" type="text" placeholder="请输入商品原价" clearable></el-input>
                        </el-form-item>
                        <el-form-item label="商品折扣率:" prop="discountRate">
                            <el-input style="width:400px" :disabled="true" v-model="form.discountRate" @change="handleOrignailChange" type="text" placeholder="请输入折扣率 (0-10之间的整数或一位小数)" clearable> </el-input>
                        </el-form-item>
                        <el-form-item label="商品折扣价:" prop="discountPrice" v-if="form.goodsPrice != ''">
                            <el-input style="width:400px" v-model="form.discountPrice" @change="changeDiscountPrice" type="text" placeholder="请输入商品折扣价" ></el-input>
                        </el-form-item>
                        <el-form-item v-else label="商品折扣价:" prop="discountPrice" >
                            <el-input disabled style="width:400px" v-model="form.discountPrice" @change="changeDiscountPrice" type="text" placeholder="请输入商品折扣价" ></el-input>
                        </el-form-item>
                        <el-form-item label="会员折扣率:" prop="memberRate">
                            <el-input style="width:400px" :disabled="true" v-model="form.memberRate" @change="changeMemberRate" type="text" placeholder="请输入商品折扣价" ></el-input>
                        </el-form-item>
                        <el-form-item label="会员折扣价:" prop="memberPrice">
                            <el-input style="width:400px" v-model="form.memberPrice" @change="changeMemberPrice" type="text" placeholder="请输入商品折扣价" clearable></el-input>
                        </el-form-item>
                        <el-form-item label="商品卖点:" >
                            <el-input type='textarea' :rows="5" style="width:400px" v-model="form.usp" :maxlength="50" placeholder="商品卖点50个字符以内"></el-input>
                        </el-form-item>
                        <el-form-item label="商品状态:" prop="soldout">
                            <el-checkbox disabled v-model="status">{{status ? '有效': '无效'}}</el-checkbox>
                        </el-form-item>
                        <el-form-item label="商品图片:" prop="isGoodsImage">
                                <el-radio v-model="form.isGoodsImage" label="0">有图商品</el-radio>
                                <el-radio v-model="form.isGoodsImage" label="1">无图商品</el-radio>
                        </el-form-item>
                    </section>
                    <el-form-item label="副图片:" class="uploadWrap" v-loading="commonImgUploadLoading" v-if="form.isGoodsImage == 0">
                        <draggable v-model="form.commonGoodsImg">
                            <transition-group>
                                <div class="prevImg" :key="index" v-for="(item,index) in form.commonGoodsImg" v-if="form.commonGoodsImg.length > 0">
                                    <img width="200" :src="item" alt="" />
                                    <i class="el-icon-error" @click="deleteCommonImgList(form,index)"></i>
                                </div>
                            </transition-group>
                        </draggable>
                        <template v-if="form.commonGoodsImg.length < 8" >
                            <div class="upload">
                                <input class="file" name="file" type="file" accept="image/png,image/gif,image/jpeg" multiple @change="commonUpload($event)" />
                                <i class="el-icon-plus"></i>
                            </div>
                        </template>
                        <p class="red">
                            <small>最多可选择8张(第一张图片为商品封面图)</small>
                        </p>
                        <p class="red">
                            <small>建议尺寸：图片尺寸小于400KB</small>
                        </p>
                    </el-form-item>
                </div>
                <div id="box">
                    <div class='addGoods-1' v-for='(item,idx) in paramList' :key="item.id">
                        <section>
                            <ul>
                                <li>
                                    <el-form-item label="单独设置价格:" >
                                        <el-switch  v-model="item.setPrice"></el-switch>
                                    </el-form-item>
                                    <section class="setPrice" v-if="item.setPrice">
                                        <el-form-item label="商品原价:">
                                            <el-input v-model="item.goodsPrice" @blur="setOrignailChange(idx,$event)" :data-idx="idx" type="text" placeholder="请输入商品原价" clearable></el-input>
                                        </el-form-item>
                                        <el-form-item label="商品折扣率:">
                                            <el-input :disabled="true" v-model="item.discountRate" @blur="setOrignailChange(idx,$event)" :data-idx="idx" type="text" placeholder="请输入折扣率 (0-10之间的整数或一位小数)" clearable> </el-input>
                                        </el-form-item>
                                        <el-form-item label="商品折扣价:">
                                            <el-input v-model="item.discountPrice" @blur="setChangeDiscountPrice(idx,$event)" :data-idx="idx" type="text" placeholder="请输入商品折扣价" ></el-input>
                                        </el-form-item>
                                        <el-form-item label="会员折扣率:">
                                            <el-input :disabled="true" v-model="item.memberRate" @blur="setChangeMemberRate(idx,$event)" :data-idx="idx" type="text" placeholder="请输入商品折扣价" ></el-input>
                                        </el-form-item>
                                        <el-form-item label="会员折扣价:">
                                            <el-input v-model="item.memberPrice" @blur="setChangeMemberPrice(idx,$event)" type="text" placeholder="请输入商品折扣价" clearable></el-input>
                                        </el-form-item>
                                    </section>
                                    <el-form-item label="商品规格:" prop="goodsColor">
                                        <el-input style="width:300px" v-model="item.goodsColor" type="text" placeholder="请输入商品颜色" clearable></el-input>
                                    </el-form-item>
                                    <el-form-item label="商品SKU:" prop="goodsSku">
                                        <el-input style="width:300px" v-model="item.goodsSku" type="text" placeholder="请输入商品SKU码,sku码唯一" clearable></el-input>
                                    </el-form-item>
                                    <el-form-item label="商品库存:" prop="stock">
                                        <ul class='stock'>
                                            <li  :key='item1.id' v-for="item1 in item.goodsSize">
                                                <el-input style="width:130px;" v-model="item1.size" type="text" placeholder="尺码" clearable></el-input>
                                                :
                                                <el-input style="width:80px;" v-model="item1.num" type="text" placeholder="数量" clearable></el-input>
                                                商品条码
                                                :
                                                <el-input style="width:200px;" v-model="item1.barCode" type="text" placeholder="商品条码必填" clearable></el-input>
                                            </li>
                                        </ul>
                                        <div class="addSize" style="margin:5px">
                                            <el-button style="float:left" type="primary" @click="addgoodsSize(idx)">新增</el-button>
                                        </div>
                                    </el-form-item>
                                    <el-form-item label="商品轮播:" class="uploadWrap " v-loading="uploadLoading" v-if="form.isGoodsImage == 0">
                                        <draggable v-model="item.goodsImg">
                                            <transition-group>
                                                <div class="prevImg" :key="index" v-for="(item1,index) in item.goodsImg" v-if="item.goodsImg.length > 0">
                                                    <img width="200" :src="item1" alt="" />
                                                    <i class="el-icon-error" @click="deleteImgList(item,index)"></i>
                                                </div>
                                            </transition-group>
                                        </draggable>
                                        <template v-if="item.goodsImg.length < 9">
                                            <div class="upload">
                                                <input class="file" name="file" type="file" accept="image/png,image/gif,image/jpeg" multiple @change="upload(idx,$event)" />
                                                <i class="el-icon-plus"></i>
                                            </div>
                                        </template>
                                        <p class="red">
                                            <small>最多可选择9张(第一张图片为商品封面图)</small>
                                        </p>
                                        <p class="red">
                                            <small>建议尺寸：图片尺寸小于400KB</small>
                                        </p>
                                    </el-form-item>
                                    <section class="addColor">
                                        <el-button type="primary" v-if="idx === paramList.length - 1"  @click="addgoodsItem('other')">新增规格</el-button>
                                        <el-button type="primary" @click="delColor(idx)">删除</el-button>
                                    </section>
                                </li>
                            </ul>
                        </section>
                    </div>
                </div>

            </el-form>
            <section class="submit" style="margin:20px">
                <el-button type="primary" @click="submit">确定</el-button>
                <el-button type="primary" style="margin-left:10px" @click="$router.go(-1)">返回</el-button>
            </section>
        </div>
    </div>
</template>
<script>
import draggable from "vuedraggable";
import {
    getProducts,
    addGoods,
    getGoodsDetailsNew,
    updateGoods,
    updateGoodsStatus,
    getQiniuToken,
    qiniuBaseUrl,
    getCategory,
    getTagByStoreNo,
    getBrand,
    allActivityList,
    getActivityDetail,
    addMultiGoods,
    getQiniuTokenVideo
} from "../../data/postData";
export default {
    components: {
        draggable
    },
    data() {
        return {
            user: JSON.parse(localStorage.getItem("ddaigoUser")),
            getTagByStoreNo: null,
            form: {
                goodsName: "",
                goodsPrice: "",
                storeNo: "",
                categoryId: "",
                goodsPic: "",
                soldout: "",
                brandId: "",
                goodsDesc: "",
                activityId: "",
                purchaseCost: "0",
                storePrice: "0",
                discountPrice: "",
                discountRate: "",
                memberPrice: "",
                memberRate: 9,
                goodsCode:'',
                commonGoodsImg:[],
                sort:'1',
                usp: '', //一句话卖点
                videoUrl: '', //视频url
                isGoodsImage: '0'//图片标识
            },
            videoloadLoading:false,
            hotSaleStatus: false, // 是否为爆款
            presaleTime: new Date(`${new Date().getFullYear()}-
                        ${new Date().getMonth() + 1}
                        ${new Date().getDate()} 20:30:00`), // 爆款开始时间
            dataForm: null,
            activityStatus: "",
            activityArr: [],
            status: true,
            disabled: false,
            addGoodsVal: null,
            paramList: [],
            brandArray: [],
            isShow1: false,
            goodsItemCount: [], // 商品款数数组
            goodsItemCountVal:'',// 商品款数值
            commonImgUploadLoading:false,// 副图片Loading
            soltArray: [
                {
                    value: "0",
                    label: "上架"
                },
                {
                    value: "1",
                    label: "下架"
                }
            ],
            categoryId: "",
            goodsItem: [],
            selGoodItemVal: [],
            isShowGoodsItem: false,
            goodsItem1: [],
            goodsItem2: [],
            goodsItem3: [],
            textarea: "",
            discount: false,
            coverUploadLoading: false,
            uploadLoading: false,
            rules: {
                goodsName: [
                    {
                        required: true,
                        message: "请输入商品名称",
                        trigger: "blur"
                    }
                ],
                goodsPrice: [
                    {
                        required: true,
                        message: "请输入商品原价",
                        trigger: "blur"
                    }
                ],
                goodsCode:[
                    {
                        required: true,
                        message: "请输入商品编号",
                        trigger: "blur"
                    }
                ],
                discountRate: [
                    {
                        required: true,
                        message: "请输入商品折扣价",
                        trigger: "blur"
                    },
                    {
                        validator: function(rule, value, callback) {
                            if (!/^\d(\.\d)?$/.test(value)) {
                                callback(
                                    new Error("正确输入折扣率：例'9'或'9.5'")
                                );
                                value = "";
                            } else {
                                callback();
                            }
                        },
                        trigger: "blur"
                    }
                ],
                memberRate: [
                    {
                        required: true,
                        message: "请输入会员折扣价",
                        trigger: "blur"
                    },
                    {
                        validator: function(rule, value, callback) {
                            if (!/^\d(\.\d)?$/.test(value)) {
                                callback(
                                    new Error("正确输入折扣率：例'9'或'9.5'")
                                );
                                value = "";
                            } else {
                                callback();
                            }
                        },
                        trigger: "blur"
                    }
                ],
                soldout: [
                    {
                        required: true,
                        message: "请选择商品状态",
                        trigger: "blur"
                    }
                ],
                memberPrice: [
                    {
                        required: true,
                        message: "请选择会员折扣价",
                        trigger: "blur"
                    },
                    {
                        validator: function(rule, value, callback) {
                            if (!/^\d+(\.\d(\d)?)?$/.test(value)) {
                                callback(
                                    new Error(
                                        "正确输入会员折扣价：保留两位小数"
                                    )
                                );
                            } else {
                                callback();
                            }
                        },
                        trigger: "blur"
                    }
                ],
                category: [
                    {
                        required: true,
                        message: "请选择商品类目",
                        trigger: "blur"
                    }
                ],
                brandArray: [
                    {
                        required: true,
                        message: "请选择商品品牌",
                        trigger: "blur"
                    }
                ],
                activityArray: [
                    {
                        required: true,
                        message: "请选择活动专场",
                        trigger: "blur"
                    }
                ],
                storePrice: [
                    { required: true, message: "请输入平台价", trigger: "blur" }
                ],
                discountPrice: [
                    {
                        required: true,
                        message: "请输入折扣价",
                        trigger: "blur"
                    },
                    {
                        validator: function(rule, value, callback) {
                            if (!/^\d+(\.\d(\d)?)?$/.test(value)) {
                                callback(
                                    new Error("正确输入折扣价：保留两位小数")
                                );
                            } else {
                                callback();
                            }
                        },
                        trigger: "blur"
                    }
                ],
                sort: [
                    {
                        required: true,
                        message: "请输入排序",
                        trigger: "blur"
                    },
                    {
                        validator: function(rule, value, callback) {
                            if (!/^\d+$/.test(+value) || +value < 1) {
                                callback(
                                    new Error("正确输入折扣率：例1、2、3")
                                );
                            } else {
                                callback();
                            }
                        },
                        trigger: "blur"
                    }
                ],
            }
        };
    },
    mounted() {
      
        // 设置款数
        for (let i = 1; i <= 20; i++) {
            this.goodsItemCount.push({
                label: i,
                value: i
            })
            
        }
        // 获取三级列表的第一级
        // this.$fetch.get(getCategory + "?categoryId=0").then(res => {
        //     this.goodsItem1 = res.data;
        // });
        var params = {
            data: {}
        };
        this.$fetch
            .post(getBrand, params)
            .then(res => {
                res.data.forEach((item, i) => {
                    this.brandArray.push({
                        value: item.id,
                        label: item.name
                    });
                });
            })
            .catch(err => {});

        var params1 = {
            data: {
                storeNo: this.user.storeNo
            }
        };
        this.$fetch
            .post(allActivityList, params1)
            .then(res => {
                var activity = [];
                res.data.forEach((val, i) => {
                    activity.push({ value: val.id, label: val.name });
                });
                this.activityArr = activity;
            })
            .catch(err => {});
        // this.getActivity(）
    },
    methods: {
        //上传视频
        
            
        deleteVideoList(){
            this.form.videoUrl = ''
        },
        // 商品款数变化
        goodsItemCountChange(val){
            this.paramList = []
            for (let i = 0; i < val; i++) {
                this.addgoodsItem()
            }
        },
        //获取活动列表
        getActivity() {
            let params = {
                data: {
                    id: "" + this.form.activityId,
                    storeNo: this.user.storeNo
                }
            };
            this.$fetch.post(getActivityDetail, params).then(res => {
                this.activityStatus = res.data.status;
            });
        },
        clickImage(index) {
            this.imageNum = index;
            this.isShow1 = true;
        },
        closeImage() {
            this.isShow1 = false;
        },
        // 会员折扣率变动
        changeMemberRate() {
            let { memberRate, discountPrice, memberPrice } = this.form;
            if (memberRate && discountPrice) {
                this.form.memberPrice =
                    Math.round(discountPrice * memberRate) / 10;
            }
        },
        // 会员价变化
        changeMemberPrice() {
            let { memberRate, discountPrice, memberPrice } = this.form;
            if (+memberPrice > +discountPrice) {
                this.$message({
                    message: "会员折扣价不能大于商品折扣价",
                    type: "warning",
                    duration: 1500
                });
            } else if (memberPrice && discountPrice) {
                this.form.memberRate =
                    Math.round(memberPrice / discountPrice * 100) / 10;
            }
        },
        // 折扣价变动
        changeDiscountPrice() {
            this.form.discountRate = "";
            if (
                this.form.goodsPrice &&
                this.form.goodsPrice != "" &&
                this.form.discountPrice &&
                this.form.discountPrice != ""
            ) {
                this.form.discountRate =
                    Math.round(
                        (+this.form.discountPrice - +this.form.storePrice) *
                            100 /
                            +this.form.goodsPrice
                    ) / 10;
            }
            this.changeMemberPrice();
            this.changeMemberRate();
        },
        // 处理原价变动
        handleOrignailChange() {
            if (
                this.form.discountRate &&
                this.form.discountRate != "" &&
                this.form.goodsPrice &&
                this.form.goodsPrice != ""
            ) {
                this.form.discountPrice =
                    Math.round(
                        this.form.goodsPrice * this.form.discountRate / 10
                    );
            }
            this.changeMemberPrice();
            this.changeMemberRate();
        },
        //////////////////////////////
        // 单独定价折扣价变动
        setChangeDiscountPrice(idx) {
            this.paramList[idx].discountRate = "";
            if (
                this.paramList[idx].goodsPrice &&
                this.paramList[idx].goodsPrice != "" &&
                this.paramList[idx].discountPrice &&
                this.paramList[idx].discountPrice != ""
            ) {
                this.paramList[idx].discountRate =
                    Math.round((+this.paramList[idx].discountPrice) * 100 / +this.paramList[idx].goodsPrice) / 10;
            }
            this.setChangeMemberPrice(idx);
            this.setChangeMemberRate(idx);
        },
        // 单独定价处理原价变动
        setOrignailChange(idx) {
            if (
                this.paramList[idx].discountRate &&
                this.paramList[idx].discountRate != "" &&
                this.paramList[idx].goodsPrice &&
                this.paramList[idx].goodsPrice != ""
            ) {
                this.paramList[idx].discountPrice =
                    Math.round(
                        this.paramList[idx].goodsPrice * this.paramList[idx].discountRate / 10
                    ) ;
            }
            this.setChangeMemberPrice(idx);
            this.setChangeMemberRate(idx);
        },
        // 单独定价会员折扣率变动
        setChangeMemberRate(idx) {
            let { memberRate, discountPrice, memberPrice } = this.paramList[idx];
            if (memberRate && discountPrice) {
                this.paramList[idx].memberPrice =
                    Math.round(discountPrice * memberRate) / 10;
            }
        },
        // 单独定价会员价变化
        setChangeMemberPrice(idx) {
            let { memberRate, discountPrice, memberPrice } = this.paramList[idx];
            if (+memberPrice > +discountPrice) {
                this.$message({
                    message: "会员折扣价不能大于商品折扣价",
                    type: "warning",
                    duration: 1500
                });
            } else if (memberPrice && discountPrice) {
                this.paramList[idx].memberRate =
                    Math.round(memberPrice / discountPrice * 100) / 10;
            }
        },
        // 添加款数
        addgoodsItem(val) {
            this.paramList.push({
                setPrice: false,
                goodsColor: "",
                goodsSku:'',//待加商品SKU码
                goodsImg: [],
                discountPrice: "",
                discountRate: "",
                memberPrice: "",
                memberRate: 9,
                goodsSize: [
                    {
                        size: "S",
                        num: "0",
                        barCode:''
                    }
                ]
            });
            if(val === 'other'){
                this.goodsItemCountVal = this.paramList.length 
            }
        },
        // 添加库存尺码
        addgoodsSize(e) {
            this.paramList[e].goodsSize.push({
                size: "",
                num: "0",
                barCode:''
            });
        },
        // 删除颜色
        delColor(idx) {
            this.paramList.splice(idx, 1);
            this.goodsItemCountVal = this.paramList.length 
        },
        message(msg, icon) {
            this.$message({
                message: msg,
                type: icon ? icon : "error"
            });
        },
        submit() {
            let {
                goodsName,
                goodsPrice,
                storeNo,
                categoryId,
                goodsPic,
                soldout,
                brandId,
                goodsDesc,
                activityId,
                purchaseCost,
                storePrice,
                discountPrice,
                discountRate,
                memberPrice,
                memberRate,
                goodsCode,
                commonGoodsImg,
                sort,
                usp,
                isGoodsImage
            } = this.form
            let filter,
                isAllow = true;
            if (goodsName.trim() === "") {
                this.message("商品名称不能为空");
            } else if (this.hotSaleStatus && (this.presaleTime === "" || this.presaleTime === 0)) {
                this.message("请输入爆款开始时间");
            } else if (brandId === "") {
                this.message("选择商品品牌")
            } else if (activityId === "") {
                this.message("选择商品活动")
            } else if (String(goodsPrice).trim() === "") {
                this.message("商品原价不能为空");
            } else if (String(discountRate).trim() === "") {
                this.message("商品折扣率不能为空");
            } else if (String(memberRate).trim() === "") {
                this.message("会员折扣率不能为空");
            } else if (String(goodsCode).trim() === '') {
                this.message("请输入商品编号")
            }else if (this.goodsItemCountVal === '') {
                this.message("请添加规格")
            }else if (sort.trim() === '') {
                this.message("请输入排序")
            }else{
                let colors = [];
                for (let i = 0; i < this.paramList.length; i++) {
                    const val = this.paramList[i];
                    if(val.setPrice){
                        if(val.discountPrice == '' || val.discountRate == '' || val.memberPrice == '' || val.memberRate == ''){
                            this.message(`请正确填写第${i + 1}个的价格信息`)
                            isAllow = false
                            break
                        }
                    }
                    if (colors.indexOf(val.goodsColor) >= 0) {
                        this.message(`商品规格重复！`)
                        isAllow = false
                        break
                    }else{
                        colors.push(val.goodsColor)
                    }
                    let filter = val.goodsSize.filter((size,s)=>{
                        return String(size.size).trim() != '' && String(size.num).trim() != ''
                    })
                    let filterNum =  val.goodsSize.filter(size => {
                        return !/^\d+$/g.test(size.num) && size.num != '' 
                    })
                    let filterBarcode =  val.goodsSize.filter(size => {
                        return((!/^[-\_A-Za-z0-9]+$/g.test(size.barCode) && size.barCode != '' ) || size.barCode == '') && size.size != ''
                    })
                    if(filter.length === 0){
                        isAllow = false
                        this.message(`第${i + 1}个商品的库存不能为空`)
                        break
                    }else{
                        val.goodsSize = filter
                    }
                    if(filterNum.length > 0){
                        this.message(`第${i + 1}个商品的库存请填写数字`)
                        isAllow = false
                        break
                    }
                    if(filterBarcode.length > 0){
                        this.message(`第${i + 1}个商品的条码不能含有中文字符，且不为空`)
                        isAllow = false
                        break
                    }
                    if(val.goodsColor === ''){
                        this.message(`请填写第${i + 1}个商品规格`)
                        isAllow = false
                        break
                    }
                    if(val.goodsSku === ''){
                        this.message(`请填写第${i + 1}个商品SKU`)
                        isAllow = false
                        break
                    }
                    if(val.goodsImg.length === 0 && this.form.isGoodsImage == 0){
                        this.message(`请上传第${i + 1}个商品图片`)
                        isAllow = false
                        break
                    }
                    if(val.goodsImg.length + commonGoodsImg > 9){
                        this.message(`第${i + 1}个商品图片超过限制！`)
                        isAllow = false
                        break
                    }
                }
                if(isAllow){
                    this.$confirm("确认提交？").then(_ => {
                        this.paramList.forEach(val=>{
                            if(!val.setPrice){
                                val.discountPrice = '' +  discountPrice;
                                val.goodsPrice = '' +  goodsPrice;
                                val.discountRate = '' + discountRate;
                                val.memberPrice = '' + memberPrice;
                                val.memberRate = '' + memberRate;
                            }else{
                                val.discountPrice = '' +  val.discountPrice;
                                val.discountRate = '' + val.discountRate;
                                val.goodsPrice = '' +  val.goodsPrice;
                                val.memberPrice = '' + val.memberPrice;
                                val.memberRate = '' + val.memberRate;
                            }
                            val.goodsImg = val.goodsImg.concat(commonGoodsImg)
                            val.goodsPic = val.goodsImg[0];
                          
                            val.goodsSize.forEach((size,i) => {
                                size.num = +size.num
                            })
                            val.goodsCode = '' + goodsCode
                        })
                        let params = {
                            data:{
                                goodsName,
                                brandId: '' + brandId,
                                goodsDesc,
                                activityId: '' + activityId,
                                soldout: '0',
                                storeNo: this.user.storeNo,
                                styleCount: +this.goodsItemCountVal,
                                paramList: this.paramList,
                                sort,
                                categoryId: '0',
                                hotSale: '0',
                                usp,
                                isGoodsImage
                            }
                        }
                        if (this.hotSaleStatus) {
                            params.data.hotSale = '1';
                            params.data.presaleTime = +new Date(
                                this.presaleTime
                            ).getTime();
                        }
                        // return
                        this.$fetch.post(addMultiGoods,params)
                            .then(res=>{
                                this.message(res.message,'success')
                                setTimeout(() => {
                                    this.$router.go(-1);
                                }, 1500);
                            })
                            .catch(err => {
                                this.message(err.message);
                            });
                    })
                }
            }
        },
        hideSel(e) {
            let className = e.target.className;
            if (
                className.search("selList") < 0 &&
                className.search("selGoodsItem") < 0 &&
                className.search("gray") < 0
            ) {
                this.isShowGoodsItem = false;
            }
        },
        // // 多级项目选择
        selGoodsItem(res) {
            this.isShowGoodsItem = true;
            this.goodsItem2 = [];
            this.goodsItem3 = [];
            this.goodsItem = [];
        },
        loadTwo(val, name) {
            this.goodsItem = [];
            this.goodsItem.push({
                val: val,
                name: name
            });
            this.$fetch.get(getCategory + "?categoryId=" + val).then(res => {
                this.goodsItem2 = res.data;
            }).catch(err => {
                this.message(err.message, "error");
            });
        },
        loadTree(val, name) {
            this.$fetch.get(getCategory + "?categoryId=" + val).then(res => {
                this.goodsItem[1] = {
                    val: val,
                    name: name
                };
                this.goodsItem3 = res.data;
            }).catch(err => {
                this.message(err.message, "error");
            });
        },
        selDone(val, name) {
            this.goodsItem[2] = {
                val: val,
                name: name
            };
            this.isShowGoodsItem = false;
        },
        // 副图片上传
        commonUpload(e){
            const that = this;
            var files = e.target.files;
            for (let i = 0; i < files.length; i++) {
                // let width, height;
                // let reader = new FileReader();
                // reader.onload = function(e) {
                //     var image = new Image();
                //     image.onload = function() {
                //         width = image.width;
                //         height = image.height;
                //         if (width >= 400 && height >= 400 && width == height) {
                            if(files[i].size / 1000 <= 400){
                                that.commonImgUploadLoading = true;
                                that.$http.get(getQiniuToken, {
                                    params: {
                                        wxUid: "",
                                        wxSid: ""
                                    }
                                }).then(res1 => {
                                    let config = {
                                        headers: {      
                                            "Content-Type":
                                            "multipart/form-data"
                                        }
                                    };
                                    let formdata = new FormData(); //创建form对象
                                    formdata.append(
                                        "file",
                                        files[i],
                                        files[i].name
                                    );
                                    formdata.append("chunk", "0"); //断点传输
                                    formdata.append("chunks", "1");
                                    formdata.append("token", res1.data.uptoken);
                                    // http://goods.dingdian.xin 图片上传地址
                                    that.$http.post("http://up-z1.qiniup.com",formdata,config).then(res2 => {
                                        if (res2.data.key != "" && i < 8) {
                                            // 加判断是第几个商品
                                            that.form.commonGoodsImg.push(qiniuBaseUrl +res2.data.key +"?imageMogr2/thumbnail/300000@")
                                            that.form.commonGoodsImg = that.form.commonGoodsImg.slice(0,8)
                                            that.$message({
                                                title: "提示",
                                                message: "图片上传成功",
                                                type: "success",
                                                duration: 1500
                                            });
                                        }
                                        that.commonImgUploadLoading = false;
                                    });
                                });
                            }else{
                                that.$message.warning(`上传图片大于400KB`)
                            }
                //         } else {
                //             that.$message({
                //                 title: "提示",
                //                 message: "上传图片尺寸要求不小于400*400方图",
                //                 type: "warning"
                //             });
                //         }
                //     };
                //     image.src = e.target.result;
                // };
                // reader.readAsDataURL(files[i]);
            }
        },
        //限制图片750*750
        upload(idx, e) {
            const that = this;
            var files = e.target.files;
            for (let i = 0; i < files.length; i++) {
                let width, height;
                // let reader = new FileReader();
                // reader.onload = function(e) {
                //     var image = new Image();
                //     image.onload = function() {
                //         width = image.width;
                //         height = image.height;
                //         if (width >= 400 && height >= 400 && width == height) {
                            if(files[i].size / 1000 <= 400){
                                that.uploadLoading = true;
                                that.$http
                                    .get(getQiniuToken, {
                                        params: {
                                            wxUid: "",
                                            wxSid: ""
                                        }
                                    })
                                    .then(res1 => {
                                        let config = {
                                            headers: {
                                                "Content-Type":
                                                    "multipart/form-data"
                                            }
                                        };
                                        let formdata = new FormData(); //创建form对象
                                        formdata.append(
                                            "file",
                                            files[i],
                                            files[i].name
                                        );
                                        formdata.append("chunk", "0"); //断点传输
                                        formdata.append("chunks", "1");
                                        formdata.append("token", res1.data.uptoken);
                                        // http://goods.dingdian.xin 图片上传地址
                                        that.$http.post(
                                            "http://up-z1.qiniup.com",
                                            formdata,
                                            config
                                        ).then(res2 => {
                                            if (res2.data.key != "" && i < 9 - this.form.commonGoodsImg.length) {
                                                // 加判断是第几个商品
                                                that.paramList[
                                                    idx
                                                ].goodsImg.push(
                                                    qiniuBaseUrl +
                                                        res2.data.key +
                                                        "?imageMogr2/thumbnail/300000@"
                                                );
                                                that.paramList[
                                                    idx
                                                ].goodsImg = that.paramList[
                                                    idx
                                                ].goodsImg.slice(0, 9 - this.form.commonGoodsImg.length);
                                                that.$message({
                                                    title: "提示",
                                                    message: "图片上传成功",
                                                    type: "success",
                                                    duration: 1500
                                                });
                                            }
                                            that.uploadLoading = false;
                                        });
                                    });
                            }else{
                                that.$message.warning('图片大小不超过400KB')
                            }
                //         } else {
                //             that.$message({
                //                 title: "提示",
                //                 message: "上传图片尺寸要求不小于400*400方图",
                //                 type: "warning"
                //             });
                //         }
                //     };
                //     image.src = e.target.result;
                // };
                // reader.readAsDataURL(files[i]);
            }
        },
        // 删除公共图片
        deleteCommonImgList(form,id){
            form.commonGoodsImg.splice(id, 1);
        },
        // 删除不同款式的图片
        deleteImgList(idx, id) {
            idx.goodsImg.splice(id, 1);
        },
        goToPrev(item, idx) {
            let newImg = item.goodsImg.slice();
            if (idx > 0) {
                let now = newImg[idx].toString();
                let prev = newImg[idx - 1].toString();
                newImg[idx] = prev;
                newImg[idx - 1] = now;
            }
            item.goodsImg = newImg;
        }
    }
};
</script>

<style scoped lang="less">
@import url("../../style/activity.less");
@import url("../../style/goods.less");
.activity-right {
    h3 {
        margin-bottom: 20px;
    }
}
.formLeft,.formRight{
    display: inline-block
}

.setPrice{
    // display: flex;
    width: 80%;
    & > div{
        display: inline-block;
    }
}
.stock {
    display: inline-block;
    margin-top: -10px;
    margin-left: -10px;;
    li {
        float: left;
        margin: 10px;
        
        input {
            width: 40px;
        }
    }
}
.addGoods-1 {
    margin-top: 20px;
    border-bottom: 2px solid #000;
}
.addColor {
    margin-bottom: 10px;
    margin-left: 80%;
}
.form {
    margin-bottom: 20px;
    border-bottom: 2px solid #000;
}
</style>